﻿using System;
using System.Web;
using Microsoft.AspNetCore.Http;

namespace QW.Core.Web
{
    /// <summary>
    /// 网页辅助
    /// </summary>
    public class Cookie
    {
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="name"></param>
        public static void Delete(string name)
        {
            HttpContext.Current.Response.Cookies.Delete(name);
        }
        /// <summary>
        /// 获取指定Cookie值
        /// </summary>
        /// <param name="name">cookiename</param>
        /// <returns></returns>
        public static string GetValue(string name)
        {
            string result = string.Empty;
            HttpContext.Current.Request.Cookies.TryGetValue(name, out result);

            return result;
        }
        /// <summary>
        /// 添加一个Cookie
        /// </summary>
        /// <param name="name">cookie名</param>
        /// <param name="value">cookie值</param>
        /// <param name="expires">过期时间 DateTime</param>
        /// <param name="domain">域</param>
        public static void SetValue(string name, string value, DateTime? expires = null, string domain = "")
        {
            bool needcko = false;
            var cko = new CookieOptions();
            if (expires != null)
            {
                needcko = true;
                cko.Expires = expires;
            }
            if (!string.IsNullOrWhiteSpace(domain))
            {
                needcko = true;
                cko.Domain = domain;
            }
            if (needcko)
            {
                HttpContext.Current.Response.Cookies.Append(name, value, cko);
            }
            else
            {
                HttpContext.Current.Response.Cookies.Append(name, value);
            }
        }
    }
}
